var settings  = require("../settings.js");
var cookies   = require("./cookies.js");
var utils     = require("../utils.js");
var DBClasses = require("../modules/DBClasses.js");
var DB        = require("../modules/mdb.js").DB;
var Query     = require("../modules/Query.js").Query;
var Update    = require("../modules/Update.js").Update;

var cookieName = cookies.cookieName;
var User       = DBClasses.User;

exports.setting_handler  = setting_handler;
exports._setting_handler = _setting_handler;

exports.active_handler = active_handler;

function setting_handler(req,res){

    res.render("user",{title:"修改用户信息"});
}

function _setting_handler(req,res){

    var body = req.body;
    
    var db = new DB();
    var query = new Query();
    query.start("email").eq(req.cookies[cookieName.userid]).done();
    
    db.findOne(settings.userCollection,query,
	       //! i still not find the propery way to handler the err redirect
	       //! will come back later
	       function(err){
		   //*
		   console.log(err);
		   res.locals.error = "server internal error.";
		   res.locals.user = null;
		   return res.redirect("/");
	       },
	       function(doc){
		   if(!doc){
		       //*
		       res.locals.error = "database internal error.";
		       res.locals.user = null;
		       return res.redirect("/");
		   }
		   var user = new User(doc.real_name,doc.age,
					      doc.email,doc.mobile,doc.password,
					      doc.address,doc.profession,
					      doc.permissions);
		   
		   user.mobile = body.phone;
		   user.real_name = body.name;
		   user.address = body.address;		   
		   user.age = body.age;
		   user.profession = body.job;
		   
		   var update = new Update();
		   
		   update
		       .reset("mobile",user.mobile).
		       reset("real_name",user.real_name).
		       reset("address",user.address).
		       reset("age",user.age).
		       reset("profession",user.profession);
		   
		   db.modify(settings.userCollection,
			     query,update,
			     function(err){
				 //!!!!!
				 console.log(err);
				 res.locals.error = "db internal error";
				 return res.redirect("/");

			     },
			     function(){
				 res.locals.user = user;
				 return res.redirect("/");
			     });
		       
	       });
    
	       
}


function active_handler(req,res){

    
}
